package com.qining618.cms.ucenter.service.impl;

import com.alibaba.fastjson.JSON;
import com.qining618.cms.ucenter.domain.Token;
import com.qining618.cms.ucenter.domain.User;
import com.qining618.cms.ucenter.mapper.TokenMapper;
import com.qining618.cms.ucenter.service.TokenService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qining618.cms.ucenter.service.UserService;
import com.qining618.common.exception.BusinessException;
import com.qining618.common.model.AuthUser;
import com.qining618.common.model.TokenInfo;
import com.qining618.common.result.ErrorCode;
import com.qining618.common.utils.StringUtils;
import com.qining618.common.utils.time.ClockUtil;
import com.qining618.common.utils.time.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * <p>
 * 登录凭证管理 服务实现类
 * </p>
 *
 * @author qining
 * @date 2019-09-16
 */
@Transactional(readOnly = true, rollbackFor = Exception.class)
@Service
public class TokenServiceImpl extends ServiceImpl<TokenMapper, Token> implements TokenService {

    @Autowired
    private UserService userService;

    @Override
    public TokenInfo findByAccessToken(String accessToken) {
        Token token = this.baseMapper.findByToken(accessToken);
        if (token == null) {
            return null;
        }
        return TokenInfo.of(token);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String generateAccessToken(Long userId) {
        Date date = ClockUtil.currentDate();
        User user = userService.getById(userId);

        // 获取凭证
        String accessToken = StringUtils.get32UUID();

        AuthUser authUser = AuthUser.builder()
                .id(user.getId())
                .avatar(user.getAvatar())
                .username(user.getUsername())
                .isAdmin(user.getIsAdmin())
                .build();

        Token token = new Token();
        token.setAccessToken(accessToken)
                .setUserId(userId)
                .setAuthInfo(JSON.toJSONString(authUser))
                .setExpireTime(DateUtil.addDays(date, 7))
                .setCtime(date)
                .setMtime(date);

        int opNum = this.baseMapper.insert(token);
        if (opNum != 1) {
            throw new BusinessException(ErrorCode.DB_ERROR);
        }

        return accessToken;
    }
}
